package com.lagou.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DownloadFileRequest;
import com.aliyun.oss.model.OSSObject;
import com.lagou.bean.UpLoadResult;
import com.lagou.config.AliyunOSSConfig;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileUpLoadService {
    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;
    @Autowired
    private OSSClient ossClient;

    // 允许上传的格式
    private static final String[] ALLOW_IMAGE_TYPE = new String[]{".jpg", ".jpeg", ".png"};

    public UpLoadResult upload(MultipartFile multipartFile) {
        boolean isLegal = false;
        for (String type : ALLOW_IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }
        UpLoadResult upLoadResult = new UpLoadResult();
        if (!isLegal) {
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("只能上传jpg、jpeg、png格式的图片");
            return upLoadResult;
        }
        long size = multipartFile.getSize();
        if (size > 5 * 1024 * 1024) {
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("图片大小不能超过5M");
            return upLoadResult;
        }

        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        try {
            ossClient.putObject(aliyunOSSConfig.getBucketName(), filePath, new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            upLoadResult.setStatus("error");
            return upLoadResult;
        }
        upLoadResult.setStatus("done");
        upLoadResult.setName(aliyunOSSConfig.getUrlPrefix() + filePath);
        upLoadResult.setUid(filePath);
        return upLoadResult;
    }

    // 生成不重复的文件路径和文件名
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

    public void download(String fileName, HttpServletResponse response) throws IOException {
        fileName = StringUtils.substringAfter(fileName, aliyunOSSConfig.getUrlPrefix());
        OSSObject ossObject = ossClient.getObject(aliyunOSSConfig.getBucketName(), fileName);
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
        out.close();
        in.close();
    }

    public UpLoadResult delete(String fileName) {
        fileName = StringUtils.substringAfter(fileName, aliyunOSSConfig.getUrlPrefix());
        ossClient.deleteObject(aliyunOSSConfig.getBucketName(), fileName);
        UpLoadResult fileUploadResult = new UpLoadResult();
        fileUploadResult.setName(fileName);
        fileUploadResult.setStatus("success");
        fileUploadResult.setResponse("删除成功");
        return fileUploadResult;
    }
}
